package edu.hcmus.sow.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import edu.hcmus.sow.utils.SecurityUtil;

public class GlobalInterceptor extends HandlerInterceptorAdapter {
   // before the actual handler will be executed
   public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      return true;
   }

   // after the handler is executed
   public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView mav)
         throws Exception {
      if (SecurityContextHolder.getContext().getAuthentication() != null && mav != null) {
         // get authentication
         SecurityContextHolderAwareRequestWrapper wrapper = new SecurityContextHolderAwareRequestWrapper(request, "");

         // modified the existing modelAndView
         request.setAttribute("loggedinUsername", SecurityUtil.getCurrentLoggedinUsername());
         request.setAttribute("isAdmin", wrapper.isUserInRole("ROLE_ADMINISTRATOR"));
      }
   }
}